/**
 * Copyright (c) 2019 xstgongyi.org
 * All rights reserved.
 */
package org.xstgongyi.eduaid.service;

import java.time.LocalDateTime;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xstgongyi.eduaid.dataobject.ProjectPhaseDO;
import org.xstgongyi.eduaid.bo.ProjectPhaseStatus;
import org.xstgongyi.eduaid.dataobject.SemesterDO;
import org.xstgongyi.eduaid.manager.ProjectPhaseManager;
import org.xstgongyi.eduaid.manager.SemesterManager;

/**
 * @author oldcrane<br/>
 * @created 2019-04-03
 */
@Service
public class ProjectPhaseServiceImpl implements ProjectPhaseService {
	private static final ProjectPhaseStatus DEFAULT_STATUS = ProjectPhaseStatus.ongoing;

	@Autowired
	private ProjectPhaseManager projectPhaseManager;

	@Autowired
	private SemesterManager semesterManager;

	@Override
	public List<ProjectPhaseDO> listByProject(Integer projectId) {
		return projectPhaseManager.listByProject(projectId);
	}

	@Override
	public ProjectPhaseDO getById(Integer id) {
		return projectPhaseManager.getById(id);
	}

	@Override
	public List<ProjectPhaseDO> list(Integer projectId, Integer semesterId, ProjectPhaseStatus status) {
		Map<String, Object> condition = new HashMap<>();
		condition.put("projectId", projectId);
		condition.put("semesterId", semesterId);
		condition.put("status", status);
		return projectPhaseManager.list(condition);
	}

	@Override
	public void insert(Integer projectId, Integer semesterId) {
		// TODO 需要增加异常处理逻辑（检查要创建的ProjectPhase是否已经存在）
		ProjectPhaseDO projectPhaseDO = new ProjectPhaseDO();
		projectPhaseDO.setProjectId(projectId);
		projectPhaseDO.setSemesterId(semesterId);
		projectPhaseDO.setStatus(DEFAULT_STATUS);
		LocalDateTime now = LocalDateTime.now();
		projectPhaseDO.setGmtCreated(now);
		projectPhaseDO.setGmtUpdated(now);
		projectPhaseManager.insert(projectPhaseDO);
	}

	@Override
	public void updateStatus(Integer id, ProjectPhaseStatus status) {
		// TODO 需要增加异常处理逻辑（例如：id不存在）
		projectPhaseManager.updateStatus(id, status, LocalDateTime.now());
	}

	@Override
	public List<SemesterDO> listUncreatedSemesters(Integer projectId) {
		List<ProjectPhaseDO> existPhases = this.listByProject(projectId);
		Set<SemesterDO> existSemsters = new HashSet<>();
		for (ProjectPhaseDO item : existPhases) {
			SemesterDO semester = semesterManager.getById(item.getSemesterId());
			existSemsters.add(semester);
		}

		List<SemesterDO> semseters = semesterManager.listAllByStatus(true);
		List<SemesterDO> uncreatedSemsters = new ArrayList<>(16);
		for(SemesterDO item : semseters) {
			if(!existSemsters.contains(item)) {
				uncreatedSemsters.add(item);
			}
		}
		return uncreatedSemsters;
	}

}
